package com.xiepxcc.annotation.base.aop;

import com.xiepxcc.annotation.base.anno.DupNoticeAnnotation;
import com.xiepxcc.annotation.base.anno.LogAnnotation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class AccessAop {

    //    环绕通知：类似与动态代理的全过程
    @Around(value = "execution(* com.xiepxcc.annotation.base.service.*.*(..)) && @annotation(log)")
    public Object aroundMethod(ProceedingJoinPoint pjd, LogAnnotation log) {
        Object result = null;
        System.out.println(log.desc());
        try {
            System.out.println("前置通知");
            result = pjd.proceed();
            System.out.println("后置通知");
        } catch (Throwable e) {
            System.out.println("异常通知");
        }
        System.out.println("返回通知");
        return result;
    }


    //标注该方法体为异常通知，当目标方法出现异常时，执行该方法体
    @AfterThrowing(pointcut="within(com.xiepxcc.annotation.base.service..*) && @annotation(notices)", throwing="ex")
    public void addLog(JoinPoint jp, DupNoticeAnnotation  notices, Exception ex){

        System.out.println(ex.getMessage());
        Arrays.stream(notices.value()).forEach(a -> {
            System.out.println(a.value());
        });
    }
}
